package com.berchen.数据结构.队列;

/**
 * 环形队列
 */
public class RingsArrayQueue {

    private int size;
    private int head_index; // 队列头索引
    private int tail_index; // 队列尾索引
    private int count;  // 队列中元素个数
    private int[] queue;

    public RingsArrayQueue(int size) {
        this.size = size;
        queue = new int[this.size];
        this.head_index = 0;
        this.tail_index = -1;
    }

    /**
     * 判断队列是否满
     *
     * @return
     */
    public boolean isFull() {
        return count==size;
    }

    /**
     * 判断队列是否为空
     *
     * @return
     */
    public boolean isEmpty() {
        return count==0;
    }

    /**
     * 往队列里面添加元素
     *
     * @param num
     * @return
     */
    public boolean add(int num) {
        if (isFull()) return false;
        tail_index = (tail_index + 1) % size;
        queue[tail_index] = num;
        count++;
        return true;
    }

    /**
     * 获取队头元素  队头元素还在
     * @return
     */
    public int get(){
        if(isEmpty()) throw new RuntimeException("队列为空");
        return queue[head_index];
    }

    /**
     * 获取队头元素 队头元素被删除
     * @return
     */
    public int remove(){

        if(isEmpty()) throw new RuntimeException("队列为空");
        int head=queue[head_index];
        head_index=(head_index+1)%size;
        count--;
        return head;
    }

    /**
     * 展示队列中的数据 从队列头 到队列尾
     */
    public void list(){
        if(isEmpty())throw new RuntimeException("队列为空");
        int index=head_index;
        for(int i =0;i<count;i++){
            if(i==count-1){
                System.out.println(queue[index]);
            }
            else {
                System.out.print(queue[index] + ",");
            }
            index=(index+1)%size;
        }
    }
}
